
const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controler/Blog')
const { SuccessModel, ErrorModel } = require('../model/Resmodel')
const loginCheck = (req) => {
  if (!req.session.username) {
    return Promise.resolve(new ErrorModel('尚未登录'))

  }

}//作用是拦截哪些没有登录的用户进行这个新建，博客或者说删除这个博客

const HandleBlogRouter = (req, res) => {
  let method = req.method

  if (method === 'GET' && req.path === '/api/blog/list') { //获取博客的列表
    let author = req.query.author || ''
    let keyword = req.query.keyword || ''
    // let ListData = getList(author, keyword)
    // return new SuccessModel(ListData)

    if (req.query.isadmin) {
      if (req.session.username === null) {//如果mei
        res.json(new ErrorModel('未登录'))
        return//return的目的就是不让后面的代码继续执行了。
      }
      author = req.session.username
    }
    let res = getList(author, keyword)
    return res.then(listData => {

      return new SuccessModel(listData)
    }) //为什么要给这里加上一个return呢

  }
  if (method === 'GET' && req.path === '/api/blog/detail') {
    const id = req.query.id
    const result = getDetail(id)
    return result.then(data => {
      return new SuccessModel(data)
    })

  }

  /////
  if (method === 'POST' && req.path === '/api/blog/update') {
    const logincheckresult = loginCheck(req)
    if (logincheckresult) {
      return logincheckresult
    }
    const upres = updateBlog(req.query.id, req.body)
    return upres.then(val => {
      if (val) {
        return new SuccessModel()
      } else {
        return new ErrorModel('更新博客失败')
      }
    })

  }

  if (method === 'POST' && req.path === '/api/blog/new') {
    const logincheckresult = loginCheck(req)
    if (logincheckresult) {
      return logincheckresult
    }
    const author = req.session.username
    req.body.author = author//这个是因为我新建博客的时候不可能还把我是谁也传进去吧，所以我需要；
    const blogData = newBlog(req.body)
    return blogData.then(data => {
      return new SuccessModel(data)
    })




  }


  if (method === 'POST' && req.path === '/api/blog/del') {
    const logincheckresult = loginCheck(req)
    if (logincheckresult) {
      return logincheckresult
    }

    const author = req.session.username

    const deletedata = deleteBlog(req.query.id, author)
    console.log(deletedata);
    return deletedata.then(val => {
      if (val) {
        return new SuccessModel()//里面不用去传数据是因为对于post请求，我只需要知道我是否操作成功与否，里面的数据我不关注。

      } else {
        return new ErrorModel('删除博客失败')
      }

    })

  }
}





module.exports = HandleBlogRouter